<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <th:block th:include="include :: header('预算列表')" />
    <th:block th:include="include :: datetimepicker-css" />
    <link href="../static/ajax/libs/sweetalert/sweetalert.css" th:href="@{/ajax/libs/sweetalert/sweetalert.css}" rel="stylesheet"/>
    <style>
        /* 新增的现代化样式 */
        .container-div {
            padding: 20px;
            background: #f8fafc;
            border-radius: 10px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
        }

        .search-collapse {
            background: #fff;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
            box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
        }

        .select-list ul {
            display: flex;
            flex-wrap: wrap;
            margin: 0;
            padding: 0;
            list-style: none;
        }

        .select-list li {
            display: flex;
            align-items: center;
            margin-right: 15px;
            margin-bottom: 10px;
        }

        .select-list label {
            margin-right: 8px;
            font-weight: 500;
            color: #555;
            min-width: 60px;
            text-align: right;
        }

        .select-list input {
            border: 1px solid #e4e7ed;
            border-radius: 4px;
            padding: 8px 12px;
            transition: all 0.3s;
            width: 180px;
        }

        .select-list input:focus {
            border-color: #409eff;
            outline: none;
            box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
        }

        .time-input {
            background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 24 24' fill='none' stroke='%23999' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Crect x='3' y='4' width='18' height='18' rx='2' ry='2'%3E%3C/rect%3E%3Cline x1='16' y1='2' x2='16' y2='6'%3E%3C/line%3E%3Cline x1='8' y1='2' x2='8' y2='6'%3E%3C/line%3E%3Cline x1='3' y1='10' x2='21' y2='10'%3E%3C/line%3E%3C/svg%3E") no-repeat right 10px center;
            background-size: 16px;
            padding-right: 35px;
        }

        #toolbar {
            margin-bottom: 15px;
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
        }

        #toolbar .btn {
            border-radius: 4px;
            padding: 6px 12px;
            font-size: 13px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
            transition: all 0.3s;
            border: none;
        }

        #toolbar .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        }

        #toolbar .btn i {
            margin-right: 5px;
        }

        .table-striped {
            background: #fff;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
        }

        /* 表格美化 */
        #bootstrap-table {
            border-collapse: separate;
            border-spacing: 0;
        }

        #bootstrap-table thead th {
            background-color: #f8fafc;
            color: #555;
            font-weight: 600;
            border-bottom: 1px solid #e4e7ed;
            padding: 12px 15px;
        }

        #bootstrap-table tbody td {
            padding: 12px 15px;
            border-bottom: 1px solid #f0f2f5;
            transition: all 0.3s;
        }

        #bootstrap-table tbody tr:hover td {
            background-color: #f5f7fa;
        }

        #bootstrap-table .btn-xs {
            padding: 4px 8px;
            font-size: 12px;
            border-radius: 3px;
            margin-right: 5px;
        }

        /* 预算余额高亮样式 */
        .budget-balance {
            font-weight: 600;
            color: #67c23a;
        }

        .budget-balance.negative {
            color: #f56c6c;
        }

        /* 预算使用率进度条 */
        .progress-container {
            width: 100%;
            height: 20px;
            background-color: #ebeef5;
            border-radius: 10px;
            overflow: hidden;
            position: relative;
        }

        .progress-bar {
            height: 100%;
            background-color: #409eff;
            transition: width 0.6s ease;
        }

        .progress-text {
            position: absolute;
            left: 0;
            right: 0;
            text-align: center;
            font-size: 12px;
            color: #fff;
            text-shadow: 0 0 2px rgba(0,0,0,0.5);
        }

        /* 预算状态标签 */
        .budget-status {
            display: inline-block;
            padding: 3px 8px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: 600;
        }

        .status-normal {
            background-color: #e1f3d8;
            color: #67c23a;
        }

        .status-warning {
            background-color: #faecd8;
            color: #e6a23c;
        }

        .status-danger {
            background-color: #fde2e2;
            color: #f56c6c;
        }

        /* 快速筛选按钮组 */
        .quick-filter {
            margin-bottom: 15px;
        }

        .quick-filter .btn {
            margin-right: 8px;
            margin-bottom: 8px;
        }

        /* 响应式调整 */
        @media (max-width: 768px) {
            .select-list li {
                flex: 0 0 100%;
                margin-right: 0;
            }

            .select-list input {
                width: 100%;
            }

            #toolbar {
                flex-direction: column;
                align-items: flex-start;
            }
        }
    </style>
</head>
<body class="gray-bg">
<div class="container-div">
    <div class="row">
        <div class="col-sm-12 search-collapse">
            <form id="formId">
                <div class="select-list">
                    <ul>
                        <li>
                            <label>用户ID：</label>
                            <input type="text" name="userId" placeholder="请输入用户ID"/>
                        </li>
                        <li>
                            <label>类别ID：</label>
                            <input type="text" name="categoryId" placeholder="请输入类别ID"/>
                        </li>
                        <li>
                            <label>预算金额：</label>
                            <input type="text" name="budgetAmount" placeholder="请输入预算金额"/>
                        </li>
                        <li>
                            <label>预算月份：</label>
                            <input type="text" class="time-input" placeholder="请选择预算月份" name="budgetMonth"/>
                        </li>
                        <li>
                            <label>预算状态：</label>
                            <select name="budgetStatus" class="form-control">
                                <option value="">全部</option>
                                <option value="normal">正常</option>
                                <option value="warning">预警</option>
                                <option value="danger">超支</option>
                            </select>
                        </li>
                        <li>
                            <a class="btn btn-primary btn-rounded btn-sm" onclick="$.table.search()"><i class="fa fa-search"></i>&nbsp;搜索</a>
                            <a class="btn btn-warning btn-rounded btn-sm" onclick="$.form.reset()"><i class="fa fa-refresh"></i>&nbsp;重置</a>
                        </li>
                    </ul>
                </div>
            </form>
        </div>

        <!-- 快速筛选按钮组 -->
        <div class="col-sm-12 quick-filter">
            <span class="filter-label">快速筛选：</span>
            <button type="button" class="btn btn-sm btn-default" onclick="quickFilter('currentMonth')">本月预算</button>
            <button type="button" class="btn btn-sm btn-default" onclick="quickFilter('nextMonth')">下月预算</button>
            <button type="button" class="btn btn-sm btn-default" onclick="quickFilter('warning')">预警预算</button>
            <button type="button" class="btn btn-sm btn-default" onclick="quickFilter('overBudget')">超支预算</button>
            <button type="button" class="btn btn-sm btn-default" onclick="quickFilter('unused')">未使用预算</button>
        </div>

        <div class="btn-group-sm" id="toolbar" role="group">
            <a class="btn btn-success" onclick="$.operate.add()" shiro:hasPermission="system:budget:add">
                <i class="fa fa-plus"></i> 添加
            </a>
            <a class="btn btn-primary single disabled" onclick="$.operate.edit()" shiro:hasPermission="system:budget:edit">
                <i class="fa fa-edit"></i> 修改
            </a>
            <a class="btn btn-danger multiple disabled" onclick="$.operate.removeAll()" shiro:hasPermission="system:budget:remove">
                <i class="fa fa-remove"></i> 删除
            </a>
            <a class="btn btn-info" onclick="batchAdjustBudget()" shiro:hasPermission="system:budget:edit">
                <i class="fa fa-adjust"></i> 批量调整
            </a>
            <a class="btn btn-warning" onclick="$.table.exportExcel()" shiro:hasPermission="system:budget:export">
                <i class="fa fa-download"></i> 导出
            </a>
            <a class="btn btn-default" onclick="showBudgetStats()">
                <i class="fa fa-bar-chart"></i> 预算统计
            </a>
        </div>
        <div class="col-sm-12 select-table table-striped">
            <table id="bootstrap-table"></table>
        </div>
    </div>
</div>

<!-- 预算统计弹窗 -->
<div class="modal fade" id="budgetStatsModal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title">预算统计图表</h4>
            </div>
            <div class="modal-body">
                <div id="budgetChart" style="height: 400px;"></div>
                <div class="row" style="margin-top: 20px;">
                    <div class="col-md-6">
                        <div id="categoryChart" style="height: 300px;"></div>
                    </div>
                    <div class="col-md-6">
                        <div id="statusChart" style="height: 300px;"></div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>

<!-- 批量调整预算弹窗 -->
<div class="modal fade" id="batchAdjustModal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title">批量调整预算</h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal">
                    <div class="form-group">
                        <label class="col-sm-4 control-label">调整方式：</label>
                        <div class="col-sm-8">
                            <select id="adjustType" class="form-control">
                                <option value="fixed">固定值</option>
                                <option value="percent">百分比</option>
                            </select>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-4 control-label">调整值：</label>
                        <div class="col-sm-8">
                            <div class="input-group">
                                <input type="number" id="adjustValue" class="form-control" placeholder="请输入调整值">
                                <span class="input-group-addon" id="valueUnit">元</span>
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-4 control-label">操作类型：</label>
                        <div class="col-sm-8">
                            <select id="adjustOperation" class="form-control">
                                <option value="increase">增加</option>
                                <option value="decrease">减少</option>
                            </select>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" onclick="confirmBatchAdjust()">确认调整</button>
                <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
            </div>
        </div>
    </div>
</div>

<th:block th:include="include :: footer" />
<th:block th:include="include :: datetimepicker-js" />
<script src="../static/ajax/libs/sweetalert/sweetalert.min.js" th:src="@{/ajax/libs/sweetalert/sweetalert.min.js}"></script>
<script src="../static/ajax/libs/echarts/echarts.min.js" th:src="@{/ajax/libs/echarts/echarts.min.js}"></script>
<script th:inline="javascript">
    var editFlag = [[${@permission.hasPermi('system:budget:edit')}]];
    var removeFlag = [[${@permission.hasPermi('system:budget:remove')}]];
    var prefix = ctx + "system/budget";
    var budgetChart, categoryChart, statusChart;

    $(function() {
        var options = {
            url: prefix + "/list",
            createUrl: prefix + "/add",
            updateUrl: prefix + "/edit/{id}",
            removeUrl: prefix + "/remove",
            exportUrl: prefix + "/export",
            modalName: "预算",
            columns: [{
                checkbox: true
            },
            {
                field: 'budgetId',
                title: '预算ID',
                visible: false
            },
            {
                field: 'userId',
                title: '用户ID'
            },
            {
                field: 'categoryId',
                title: '类别ID'
            },
            {
                field: 'budgetAmount',
                title: '预算金额',
                formatter: function(value) {
                    return '¥' + parseFloat(value).toFixed(2);
                }
            },
            {
                field: 'usedAmount',
                title: '已用预算',
                formatter: function(value) {
                    return '¥' + parseFloat(value).toFixed(2);
                }
            },
            {
                title: '预算余额',
                formatter: function(value, row, index) {
                    const balance = row.budgetAmount - row.usedAmount;
                    var balanceClass = balance >= 0 ? 'budget-balance' : 'budget-balance negative';
                    return '<span class="' + balanceClass + '">¥' + balance.toFixed(2) + '</span>';
                }
            },
            {
                title: '使用率',
                formatter: function(value, row, index) {
                    const usageRate = (row.usedAmount / row.budgetAmount * 100).toFixed(1);
                    var progressColor = '#67c23a';
                    if (usageRate > 80) progressColor = '#e6a23c';
                    if (usageRate > 100) progressColor = '#f56c6c';

                    return '<div class="progress-container">' +
                           '<div class="progress-bar" style="width: ' + (usageRate > 100 ? 100 : usageRate) + '%; background-color: ' + progressColor + '">' +
                           '<div class="progress-text">' + usageRate + '%</div>' +
                           '</div></div>';
                }
            },
            {
                title: '状态',
                formatter: function(value, row, index) {
                    const usageRate = row.usedAmount / row.budgetAmount;
                    var statusClass = 'status-normal', statusText = '正常';

                    if (usageRate > 0.8) {
                        statusClass = 'status-warning';
                        statusText = '预警';
                    }
                    if (usageRate > 1) {
                        statusClass = 'status-danger';
                        statusText = '超支';
                    }

                    return '<span class="budget-status ' + statusClass + '">' + statusText + '</span>';
                }
            },
            {
                field: 'budgetMonth',
                title: '预算月份'
            },
            {
                title: '操作',
                align: 'center',
                formatter: function(value, row, index) {
                    var actions = [];
                    actions.push('<a class="btn btn-success btn-xs ' + editFlag + '" href="javascript:void(0)" onclick="$.operate.edit(\'' + row.budgetId + '\')"><i class="fa fa-edit"></i>编辑</a> ');
                    actions.push('<a class="btn btn-danger btn-xs ' + removeFlag + '" href="javascript:void(0)" onclick="$.operate.remove(\'' + row.budgetId + '\')"><i class="fa fa-remove"></i>删除</a>');
                    actions.push('<a class="btn btn-info btn-xs" href="javascript:void(0)" onclick="showBudgetDetail(\'' + row.budgetId + '\')"><i class="fa fa-info-circle"></i>详情</a>');
                    return actions.join('');
                }
            }]
        };
        $.table.init(options);

        // 初始化日期选择器
        $('.time-input').datetimepicker({
            format: 'yyyy-mm',
            minView: 'year',
            autoclose: true,
            language: 'zh-CN',
            todayBtn: true,
            startView: 'year'
        });

        // 调整方式切换事件
        $('#adjustType').change(function() {
            $('#valueUnit').text($(this).val() === 'fixed' ? '元' : '%');
        });
    });

    // 快速筛选
    function quickFilter(type) {
        var params = {};
        var currentDate = new Date();
        var currentYear = currentDate.getFullYear();
        var currentMonth = currentDate.getMonth() + 1;

        switch(type) {
            case 'currentMonth':
                params.budgetMonth = currentYear + '-' + (currentMonth < 10 ? '0' + currentMonth : currentMonth);
                break;
            case 'nextMonth':
                var nextMonth = currentMonth + 1;
                var nextYear = currentYear;
                if (nextMonth > 12) {
                    nextMonth = 1;
                    nextYear++;
                }
                params.budgetMonth = nextYear + '-' + (nextMonth < 10 ? '0' + nextMonth : nextMonth);
                break;
            case 'warning':
                params.budgetStatus = 'warning';
                break;
            case 'overBudget':
                params.budgetStatus = 'danger';
                break;
            case 'unused':
                params.usedAmount = 0;
                break;
        }

        $.table.search(params);
    }

    // 显示预算详情
    function showBudgetDetail(budgetId) {
        $.modal.openFull("预算详情", prefix + "/detail/" + budgetId);
    }

    // 批量调整预算
    function batchAdjustBudget() {
        var selectedRows = $.table.getSelections();
        if (selectedRows.length === 0) {
            swal("提示", "请至少选择一条预算记录", "warning");
            return;
        }

        $('#batchAdjustModal').modal('show');
    }

    // 确认批量调整
    function confirmBatchAdjust() {
        var selectedRows = $.table.getSelections();
        var adjustType = $('#adjustType').val();
        var adjustValue = $('#adjustValue').val();
        var adjustOperation = $('#adjustOperation').val();

        if (!adjustValue || isNaN(adjustValue) || parseFloat(adjustValue) <= 0) {
            swal("错误", "请输入有效的调整值", "error");
            return;
        }

        var budgetIds = selectedRows.map(function(row) {
            return row.budgetId;
        });

        swal({
            title: "确认调整吗?",
            text: "将对选中的" + selectedRows.length + "条预算记录进行调整",
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#5e72e4",
            confirmButtonText: "确认调整",
            cancelButtonText: "取消",
            closeOnConfirm: false
        }, function(isConfirm) {
            if (isConfirm) {
                $.ajax({
                    url: prefix + "/batchAdjust",
                    type: "post",
                    data: {
                        budgetIds: budgetIds.join(','),
                        adjustType: adjustType,
                        adjustValue: adjustValue,
                        adjustOperation: adjustOperation
                    },
                    success: function(result) {
                        if (result.code == 0) {
                            swal({
                                title: "成功",
                                text: "预算调整成功",
                                type: "success"
                            }, function() {
                                $('#batchAdjustModal').modal('hide');
                                $.table.refresh();
                            });
                        } else {
                            swal("错误", result.msg, "error");
                        }
                    }
                });
            }
        });
    }

    // 显示预算统计
    function showBudgetStats() {
        $.get(prefix + "/stats", function(result) {
            if (result.code == 0) {
                $('#budgetStatsModal').modal('show');
                initBudgetCharts(result.data);
            } else {
                swal("错误", result.msg, "error");
            }
        });
    }

    // 初始化统计图表
    function initBudgetCharts(data) {
        // 主预算图表
        budgetChart = echarts.init(document.getElementById('budgetChart'));
        var budgetOption = {
            title: {
                text: '月度预算趋势',
                left: 'center'
            },
            tooltip: {
                trigger: 'axis',
                formatter: function(params) {
                    var result = params[0].axisValue + '<br/>';
                    params.forEach(function(item) {
                        result += item.marker + ' ' + item.seriesName + ': ' + item.value + '元<br/>';
                    });
                    return result;
                }
            },
            legend: {
                data: ['预算金额', '已用金额', '余额'],
                bottom: 10
            },
            xAxis: {
                type: 'category',
                data: data.months
            },
            yAxis: {
                type: 'value',
                axisLabel: {
                    formatter: '{value} 元'
                }
            },
            series: [
                {
                    name: '预算金额',
                    type: 'bar',
                    data: data.budgetAmounts,
                    itemStyle: {
                        color: '#5e72e4'
                    }
                },
                {
                    name: '已用金额',
                    type: 'bar',
                    data: data.usedAmounts,
                    itemStyle: {
                        color: '#2dce89'
                    }
                },
                {
                    name: '余额',
                    type: 'line',
                    data: data.balances,
                    itemStyle: {
                        color: '#f5365c'
                    }
                }
            ]
        };
        budgetChart.setOption(budgetOption);

        // 分类预算饼图
        categoryChart = echarts.init(document.getElementById('categoryChart'));
        var categoryOption = {
            title: {
                text: '预算分类占比',
                left: 'center'
            },
            tooltip: {
                trigger: 'item',
                formatter: '{a} <br/>{b}: {c} ({d}%)'
            },
            legend: {
                orient: 'vertical',
                left: 'left',
                data: data.categoryNames
            },
            series: [
                {
                    name: '预算金额',
                    type: 'pie',
                    radius: ['50%', '70%'],
                    avoidLabelOverlap: false,
                    label: {
                        show: false,
                        position: 'center'
                    },
                    emphasis: {
                        label: {
                            show: true,
                            fontSize: '18',
                            fontWeight: 'bold'
                        }
                    },
                    labelLine: {
                        show: false
                    },
                    data: data.categoryData
                }
            ]
        };
        categoryChart.setOption(categoryOption);

        // 预算状态饼图
        statusChart = echarts.init(document.getElementById('statusChart'));
        var statusOption = {
            title: {
                text: '预算状态分布',
                left: 'center'
            },
            tooltip: {
                trigger: 'item',
                formatter: '{a} <br/>{b}: {c} ({d}%)'
            },
            legend: {
                orient: 'vertical',
                left: 'left',
                data: ['正常', '预警', '超支']
            },
            series: [
                {
                    name: '预算状态',
                    type: 'pie',
                    radius: '50%',
                    data: [
                        {value: data.normalCount, name: '正常', itemStyle: {color: '#67c23a'}},
                        {value: data.warningCount, name: '预警', itemStyle: {color: '#e6a23c'}},
                        {value: data.dangerCount, name: '超支', itemStyle: {color: '#f56c6c'}}
                    ],
                    emphasis: {
                        itemStyle: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    }
                }
            ]
        };
        statusChart.setOption(statusOption);

        // 窗口大小变化时重新调整图表大小
        $(window).resize(function() {
            budgetChart.resize();
            categoryChart.resize();
            statusChart.resize();
        });
    }
</script>
</body>
</html>